package com.mybatis.boost.generator.plugin;

import com.mybatis.boost.generator.plugin.adapter.MapperPluginAdapter;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.util.List;

/**
 * @author jearton
 * @since 2016/11/17
 */
public class FluentSetterPlugin extends MapperPluginAdapter {

    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
        if (introspectedColumn.isGeneratedAlways() || introspectedColumn.isGeneratedColumn()) {
            return false;
        }
        String fieldName = introspectedColumn.getJavaProperty();
        Method fluentMethod = new Method();
        fluentMethod.setVisibility(JavaVisibility.PUBLIC);
        fluentMethod.setReturnType(topLevelClass.getType());
        fluentMethod.setName(fieldName);
        fluentMethod.getParameters().addAll(method.getParameters());
        this.context.getCommentGenerator().addGeneralMethodComment(fluentMethod, introspectedTable);
        fluentMethod.addBodyLine("this." + fieldName + " = " + fieldName + ";");
        fluentMethod.addBodyLine("return this;");
        topLevelClass.addMethod(fluentMethod);
        return true;
    }
}
